﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Data.OleDb;
using System.IO;
using System.Data.SqlClient;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using U8SrvTrans;
using System.Configuration;
using System.Dynamic;
using U8;

namespace WebApplication1
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class postInventory : IHttpHandler
    {
        public static readonly string bz = ConfigurationManager.ConnectionStrings["conn1"].ConnectionString;

        public void ProcessRequest(HttpContext context)
        {
            string authHeader = HttpContext.Current.Request.Headers["Authorization"];
            string bearerToken = authHeader.Substring("Bearer ".Length).Trim();
            PetaPoco.Database dbw = new PetaPoco.Database(bz);

            string msg = "";
            object jsonData = "";
            FileLogHelper.WriteTxtLog("调用开始", "11");
            dynamic jsonF = new ExpandoObject();  //动态MODEL 存DATE
            dynamic res = new ExpandoObject();  //动态MODEL 返回值

            XZ_RZBfaModel RZB = new XZ_RZBfaModel();
            RZB.类型 = "存货";
            RZB.日期 = DateTime.Now;

            TokenModel model = dbw.FirstOrDefault<TokenModel>("select  * from  Token  where token=@token and  DATEDIFF(DAY,date, GETDATE())=0", new { token = bearerToken });
            if (model == null)
            {
                res.code = 401;
                res.msg = "密钥不合法或者已经过期";
                res.data = "XXXX";
                res.count = 0;
                jsonData = JsonConvert.SerializeObject(res);
                context.Response.Write(jsonData);
            }
            else
            {
                try
                {
                    string name = "demo";
                    string pass = "";
                    String sSubId = "AS";
                    String sAccID = ConfigurationManager.AppSettings["ZTH"].ToString();
                    String sYear = DateTime.Now.Year.ToString();
                    String sDate = DateTime.Now.ToString("yyyy-MM-dd");
                    String sServer = ConfigurationManager.AppSettings["SERVER"].ToString();
                    String sUserID = name; ;
                    String sSerial = "";
                    U8Login.clsLogin u8Login = new U8Login.clsLogin();
                    if (!u8Login.Login(ref sSubId, ref sAccID, ref sYear, ref sUserID, ref pass, ref sDate, ref sServer, ref sSerial))
                    {
                        res.msg = u8Login.ShareString;
                        res.Code = "999";
                        return;
                    }




                    byte[] postData = new byte[context.Request.InputStream.Length];
                    context.Request.InputStream.Read(postData, 0, postData.Length);
                    string postDataString = System.Text.Encoding.UTF8.GetString(postData);
                    FileLogHelper.WriteTxtLog("调用开始", postDataString);


                    RZB.JSON = postDataString;



                    InventoryModel U8fa = JsonConvert.DeserializeObject<InventoryModel>(postDataString);
                    InventoryModel inventory = U8fa;
                    RZB.返回ID = U8fa.cinvcode;

                    inventoryclassModel mod = dbw.FirstOrDefault<inventoryclassModel>("select  *   from XZ_INVENTORY  where cinvccode='" + inventory.cinvccode + "'");
                    if (mod == null)
                    {
                        RZB.是否成功 = "失败";
                        RZB.错误内容 = "自定义分类找不到";
                    }



                    inventory.isupplytype = 2; //是否生产耗用
                    if (mod.内销 == "1")
                        inventory.bsale = true; //是否内销
                    if (mod.批次 == "1")
                        inventory.binvbatch = true; //是否外销
                    if (mod.采购 == "1")
                        inventory.bpurchase = true; //是否采购
                    if (mod.ATO == "1")
                        inventory.batomodel = true; //是否采购

                    if (mod.自制 == "1")
                        inventory.bself = true; //是否自制

                    if (mod.生产耗用 == "1")
                        inventory.bcomsume = true; //是否自制

                    if (mod.计件 == "1")
                        inventory.bpiece = true; //是否生产耗用

                    if (mod.领用 == "1")
                        inventory.isupplytype = 0; //是否生产耗用

                    if (mod.质检 == "1")
                        inventory.bpropertycheck = true; //是否生产耗用
                    if (mod.全检 == "1")
                        inventory.iteststyle = 0; //是否生产耗用
                    if (mod.直接领料 == "1")
                        inventory.iDrawType = 0; //是否生产耗用

                    if (mod.资产 == "1")
                        inventory.bInvAsset = true; //是否生产耗用

                    //处理基本单位
                    int row = dbw.SingleOrDefault<int>(" SELECT  count(1)  FROM ComputationGroup B   WHERE B.cGroupCode = (SELECT  cGroupCode FROM ComputationUnit  WHERE  cComunitCode = '" + U8fa.ccomunitcode + "')  and cGroupName = '无换算'");
                    if (row > 0)
                    {
                        inventory.ccomunitcode = U8fa.ccomunitcode;
                        inventory.cgroupcode = "1";
                        inventory.igrouptype = 0;
                        inventory.cshopunit = U8fa.ccomunitcode;
                    }
                    else
                    {
                        dynamic obj1 = new ExpandoObject();
                        dynamic MO = dbw.FirstOrDefault<dynamic>("SELECT  cComunitCode,iGroupType,A.cGroupCode  FROM ComputationUnit A, ComputationGroup B WHERE A.cGroupCode =   (  SELECT  cGroupCode FROM ComputationUnit  WHERE  cComunitCode = '" + U8fa.ccomunitcode + "'   AND bMainUnit = 1 ) AND bMainUnit = 0 AND A.cGroupCode = B.cGroupCode  AND B.cGroupName='有换算' ");
                        if (MO != null)
                        {
                            inventory.ccomunitcode = U8fa.ccomunitcode;
                            inventory.cgroupcode = MO.cGroupCode;
                            inventory.igrouptype = MO.iGroupType;
                            inventory.cshopunit = MO.cComunitCode;
                            inventory.csacomunitcode = MO.cComunitCode;
                            inventory.cstcomunitcode = MO.cComunitCode;
                            inventory.cpucomunitcode = MO.cComunitCode;
                            inventory.ccacomunitcode = MO.cComunitCode;
                            inventory.cproductunit = MO.cComunitCode;
                            inventory.cshopunit = MO.cComunitCode;
                        }
                    }


                    // inventory.iplandefault = 2; //计划默认属性
                    inventory.ccreateperson = "系统"; //建档人 
                    inventory.cmodifyperson = "系统"; //变更人
                    inventory.dmodifydate = DateTime.Now; //变更日期
                    inventory.itaxrate = 13;
                    inventory.iexpsalerate = 13;
                    

                    var dataXml = FileLogHelper.GetTXml(inventory);
                    var xml = File.ReadAllText("Inventory.xml").Replace("@data", dataXml);


                    IClsCommon clsCommon = new IClsCommonClass();
                    clsCommon.InitNew(u8Login);
                    bool isOk = false;
                    int ll = dbw.SingleOrDefault<int>("select  count(1)  from inventory  where cinvcode='" + inventory.cinvcode + "'");
                    if (ll == 0)
                    {
                        isOk = clsCommon.Add(xml, "Inventory", ref msg); //第一个参数为XML字符串，第二个参数为存货档案的表名，第三个参数为返回的内容
                    }
                    else
                    {
                        isOk = clsCommon.Modify(xml, "Inventory", ref msg); //第一个参数为XML字符串，第二个参数为存货档案的表名，第三个参数为返回的内容
                    }

                    if (!isOk)
                    {
                        RZB.是否成功 = "失败";
                        RZB.错误内容 = msg;
                        res.code = 999;
                        res.msg = msg;
                        return;
                    }

                    RZB.是否成功 = "成功";
                
                    res.code = 200;
                    res.msg = "CO成功";
                    res.data = jsonData;
                  

                }

                catch (Exception ee)
                {
                    RZB.是否成功 = "失败";
                    RZB.错误内容 = ee.Message;
                    if (ee.Message.Length > 50)
                    {
                        res.msg = ee.Message.Substring(0, 50);
                    }
                    else
                    {
                        res.msg = ee.Message;
                    }
                    res.code = 999;
                   
                }
                finally
                {
                    dbw.Save(RZB);
                    jsonData = JsonConvert.SerializeObject(res);
                    context.Response.ContentType = "application/json";
                    context.Response.Write(jsonData);
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public string res(string ccode, string msg, string jsonData)
        {
            string resstr = "";


            return resstr;
        }


    }
}